# coding: utf-8
import json
from abc import ABC
from pathlib import Path
from typing import Union, Literal, Dict

from pandas import DataFrame

# from ..logger import logger

ApiJsonTemplate = DataFrame(
    [
        {
            '模块名称': '测试登录',
            '接口名称': '登录',
            '用例名称': '登录成功',
            '用例描述': '用户名正确，密码正确，登录成功',
            '是否运行': True,
            '请求数据': {
                'method': 'post',
                'url': 'http://127.0.0.1:5000/api/login',
                'json': {
                    'userName': '13523539583',
                    'password': 'admin@123456',
                },
            },
            '断言': [
                {
                    '断言方式': '',
                    '预期响应内容': '操作成功',
                    '实际响应内容': 'response.json().get("msg")   # 预期响应的msg值，response为requests.Response对象',
                    '断言信息': '登录失败'
                }
            ],
            '提取数据': {
                'token': ['json', '$.data.token', 0]
            }
        }
    ]
)
UiJsonTemplate = {}


class FileEngineBase(ABC):
    fileName: Union[str, Path] = None
    encoding = 'utf-8'
    orient: str = 'records'

    def __init__(
            self,
            fileName: Union[str, Path],
            *,
            encoding: str = 'utf-8',
            orient: Literal["split", "records", "index", "table", "columns", "values", None] = 'records'
    ):
        """
        初始化文件引擎
        :param fileName: 文件路径
        :param encoding: 编码
        :param orient: 保存及打开方式
        """
        fileName = Path(fileName).absolute() if isinstance(fileName, str) else fileName
        if fileName.is_file() is False:
            logger.debug(f'{fileName} 文件不存在，已创建')
            fileName.touch(exist_ok=True)

        self.fileName = fileName
        self.encoding = encoding
        self.orient = orient

        self.dataFrame: DataFrame = self._openDataFrame()

    def _openDataFrame(self, *args, **kwargs) -> DataFrame:
        raise NotImplementedError

    def read(self, to_dict: bool = True, *args, **kwargs) -> Union[DataFrame, Dict]:
        return self.dataFrame.to_dict(orient='records') if to_dict else self.dataFrame

    def getEnableData(self):
        df = self.read(False)
        return df[df['是否启用'] == True].to_dict(orient='records')

    def write(self, *args, **kwargs):
        raise NotImplementedError

    def clear(self):
        self.fileName.unlink(missing_ok=True)
        self.fileName.touch(exist_ok=True)

    @classmethod
    def ApiTemplate(cls, fileName: Union[str, Path]):
        """
        API模板
        :param fileName:
        :return:
        """
        raise NotImplementedError

    @classmethod
    def UiTemplate(cls, fileName: Union[str, Path]):
        """
        UI模板
        :param fileName:
        :return:
        """
        raise NotImplementedError

    @classmethod
    def to_json(cls, data: DataFrame, fileName: Union[str, Path]):
        """
        将数据保存为json文件
        :param data:
        :param fileName:
        :return:
        """
        data.to_json(fileName, indent=4, force_ascii=False, orient=cls.orient)

    @classmethod
    def to_dict(cls, data: DataFrame) -> dict:
        return data.to_dict(orient=cls.orient)

    @classmethod
    def jsonFormat(cls, data: Union[dict, list]) -> str:
        """
        将数据格式化为json字符串
        :param data:
        :return:
        """
        if data:
            return json.dumps(data, indent=4, ensure_ascii=False)
        else:
            return ''
